﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using FisheryPlatform.SiteConfig;
using System.Diagnostics;
using System.IO;

namespace FisheryPlatform.Bussiness.WebRuntime
{
    public class SiteAnalyticsModule : IHttpModule
    {
        #region IHttpModule 成员
        private List<string> extensionNameList = new List<string>();
        public void Dispose()
        {
        }
        Stopwatch pageTimer = null;
        public void Init(HttpApplication context)
        {
            pageTimer = new Stopwatch();
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);

            extensionNameList.Add(".html");
            extensionNameList.Add(".htm");
            extensionNameList.Add(".aspx");
            extensionNameList.Add(".asp");
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            pageTimer.Reset();
            pageTimer.Start();
        }

        void context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;            
            pageTimer.Stop();
            var extensionName= Path.GetExtension(app.Request.Url.AbsolutePath).ToLower();
            if (extensionNameList.Contains(extensionName))
            {
                if (app.Request.UserAgent.IndexOf("LaoZhouYuYe--") != 0)
                {
                    app.Response.Write("<script type='text/javascript' src='");
                    app.Response.Write(SiteConfigManager.WebSite.JS + SiteConfigManager.AppSettings["SiteAnalyticsUrl"].Value);
                    app.Response.Write("'></script>");
                }
                app.Response.Write("<!--page time:" + pageTimer.ElapsedMilliseconds + " / ms-->");
            }            
        }

        #endregion
    }
}
